<template>
  <j-modal
    :title="title"
    :width="width"
    :visible="visible"
    :confirmLoading="confirmLoading"
    :maskClosable="false"
    :keyboard="false"
    :forceRender="true"
    switchFullscreen
    @cancel="handleCancel"
    wrapClassName="ant-modal-cust-warp"
    style="top:5%;height: 100%;overflow-y: hidden">
    <template slot="footer">
      <a-button @click="handleCancel">{{$t('inPrint.cancel')}}</a-button>
      <!-- <a-button v-if="isCanCheck" @click="handleOkAndCheck">{{$t('popup.saveReview')}}</a-button> -->
      <a-button type="primary" @click="handleOk" :disabled="confirmLoading">{{$t('commodityManagement.preservation')}}</a-button>
    </template>
    <div style="position:absolute;bottom:53px;right:0;z-index:11" v-if="showRecover && !model.id">
      <span>{{ $t('popup.recoveryPrompt') }}</span>
      <a-button type="link" @click="recover" :disabled="submitBtnDisabled">{{$t('popup.recover')}}</a-button>
      <a-button type="link" @click="lose" :disabled="submitBtnDisabled">{{$t('popup.lose')}}</a-button>
    </div>
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-row class="form-row" :gutter="24">
          <!-- 客户 -->
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('manuManagement.customer')">
              <a-select :placeholder="$t('manuManagement.selectCustomer')" v-decorator="[ 'organId' ]"
                :dropdownMatchSelectWidth="false" showSearch optionFilterProp="children">
                <div slot="dropdownRender" slot-scope="menu">
                  <v-nodes :vnodes="menu" />
                  <a-divider style="margin: 4px 0;" />
                  <div v-if="isTenant" style="padding: 4px 8px; cursor: pointer;"
                       @mousedown="e => e.preventDefault()" @click="addCustomer"><a-icon type="plus" /> {{$t('popup.newCustomers')}}</div>
                </div>
                <a-select-option v-for="(item,index) in supList" :key="index" :value="item.id">
                  {{ item.supplier }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <!-- 选择收款单 -->
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('financialManagement.selectCollectionOrder')"
              :data-title="$t('popup.relatedOrder')">
              <a-input-search :placeholder="$t('financialManagement.selectCollectionOrder')"
                @search="onSearchLinkNumber" :readOnly="true" />
            </a-form-item>
          </a-col>
          <!-- 单据日期 -->
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('setailManagement.documentDate')">
              <j-date v-decorator="['billTime', validatorRules.billTime]" :show-time="true"/>
            </a-form-item>
          </a-col>
          <!-- 单据编号 -->
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('setailManagement.documentNo')">
              <a-input :placeholder="$t('setailManagement.pleaseEnterTheDocumentNumber')" v-decorator.trim="[ 'billNo' ]" :readOnly="true"/>
            </a-form-item>
          </a-col>

          <!-- 操作员 -->
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('defaultTranslate.operator')"
              data-step="3" :data-title="$t('defaultTranslate.operator')">
              <a-input :placeholder="$t('defaultTranslate.operator')" v-decorator.trim="['userName']"
                :readOnly="true" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row class="form-row" :gutter="24">
          <a-col :lg="12" :md="12" :sm="24">
            <a-form-item :labelCol="{xs: { span: 24 },sm: { span: 4 }}" :wrapperCol="{xs: { span: 24 },sm: { span: 20 }}" :label="$t('financialManagement.notesToDocuments')">
              <a-input :placeholder="$t('reportQuery.pleaseEnterComments')" v-decorator="[ 'remark' ]" style="margin-top:8px;"/>
            </a-form-item>
          </a-col>
        </a-row>
        <j-editable-table
          :ref="refKeys[0]"
          :loading="accountTable.loading"
          :columns="accountTable.columns"
          :dataSource="accountTable.dataSource"
          :maxHeight="300"
          :rowNumber="false"
          :rowSelection="true"
          :actionButton="true"
          @inputPurchaseValueChange="onChange"
          @valueChange="onValueChange">
          <template #billNo="record">
            <div style="text-align: center;"><a @click="openDetail(record)">{{record.value}}</a></div>
          </template>
          <template #delete="record">
            <div style="text-align: center;">
              <a-popconfirm :title="$t('manuManagement.areDelete')"
                @confirm="() => removeRows(record)">
                <a-icon type="delete"></a-icon>
              </a-popconfirm>
            </div>
          </template>
          <template #rowIndex="record">
            <div style="text-align: center;">{{ record.index + 1 }}</div>
          </template>
        </j-editable-table>
        <a-row class="form-row" :gutter="24">
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('popup.titleOfAccount')">
              <a-select v-decorator="[ 'accountId',validatorRules.accountId ]">
                <a-select-option v-for="item in accountOptionList" :key="item.value" :value="item.value">
                  {{item.text}}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>

          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('setailManagement.amountCollected')">
              <a-input :placeholder="$t('popup.pleaseCollectionAmount')" v-decorator.trim="[ 'changeAmount' ]"/>
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24" v-show="false">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('setailManagement.amountCollected')">
              <a-input :placeholder="$t('popup.pleaseCollectionAmount')" v-decorator.trim="[ 'totalPrice' ]"/>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row class="form-row" :gutter="24">
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('inPrint.enclosure')">
              <div v-if="fileLoading">Loading...</div>
              <j-upload v-else :fileList="fileList" bizPath="financial"></j-upload>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-spin>
    <person-modal ref="personModalForm" @ok="personModalFormOk"></person-modal>
    <link-bill-list ref="linkBillList" @ok="linkBillListOk"></link-bill-list>
    <customer-modal ref="customerModalForm" @ok="initSupplier"></customer-modal>
    <checkDetail ref="modalDetail"></checkDetail>
  </j-modal>
</template>
<script>
  import pick from 'lodash.pick'
  import { findBySelectCus, findBySelectSup } from '@/api/api'
  import PersonModal from '../../system/modules/PersonModal'
  import { FormTypes } from '@/utils/JEditableTableUtil'
  import { JEditableTableMixin } from '@/mixins/JEditableTableMixin'
  import { FinancialModalMixin } from '../mixins/FinancialModalMixin'
  import LinkBillList from '@/views/bill/dialog/LinkBillList'
  import JUpload from '@/components/jeecg/JUpload'
  import JDate from '@/components/jeecg/JDate'
  import CustomerModal from '@/views/system/modules/CustomerModal'
  import checkDetail from '../dialog/checkDetail'
  export default {
    name: "CheckVerificationModal",
    mixins: [JEditableTableMixin, FinancialModalMixin],
    components: {
      PersonModal,
      JUpload,
      JDate,
      LinkBillList,
      CustomerModal,
      checkDetail,
      VNodes: {
        functional: true,
        render: (h, ctx) => ctx.props.vnodes,
      }
    },
    data () {
      return {
        title:this.$t('setailManagement.operation'),
        width: '1600px',
        moreStatus: false,
        // 新增时子表默认添加几行空数据
        addDefaultRowNum: 1,
        visible: false,
        model: {},
        fileList:[],
        labelCol: {
          xs: { span: 24 },
          sm: { span: 8 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        refKeys: ['accountDataTable', ],
        activeKey: 'accountDataTable',
        accountTable: {
          loading: false,
          dataSource: [],
          columns: [
            { title: this.$t('commodityManagement.delete'), width: '3%', key: 'delete', type: 'slot' },
            { title: this.$t('defaultTranslate.lineNumber'), key: 'rowIndex', width: '5%', type: 'slot' },
            { title:this.$t('manuManagement.associated'), key: 'billNo',width:'14%', type: FormTypes.slot},
            { title: '', key: 'custom1', width: '8%',type:FormTypes.hidden},
            // { title:this.$t('purchasingManagement.PreparedBy'), key: 'username',width:'14%'},
            { title:this.$t('inPrint.documentAmount'), key: 'totalPrice',width:'8%', statistics: true},
            { title:this.$t('financialManagement.checkNumber'), key: 'taxInvoiceNo',width:'14%'},
            { title:this.$t('financialManagement.notVerifiedAmount'), key: 'notReceived',width:'10%',type: FormTypes.input, statistics: true,validateRules: [{ required: true}]},
            { title:this.$t('financialManagement.verifiedAmount'), key: 'checkAmount',width: '10%', statistics: true,type: FormTypes.normal},
            { title: this.$t('popup.titleOfAccount'),key: 'accountId',width: '20%', type: FormTypes.hidden, placeholder: this.$t('inPrint.pleaseTnter')+'${title}', options: [],
              allowSearch:true, validateRules: [{ message:'${title}'+this.$t('inPrint.cannotTe') }]
            },
          ]
        },
        confirmLoading: false,
        prefixNo: 'ZPHX',
        validatorRules:{
          accountId: {
            rules: [
              { required: true, message: this.$t('popup.pleaseSelectAccount') + '!' }
            ]
          },
          organId:{
            rules: [
              { required: true, message: this.$t('popup.pleasePaymentMember')+'!' }
            ]
          },
          billTime:{
            rules: [
              { required: true, message: this.$t('popup.pleaseSelectDocumentDate')+'!' }
            ]
          },
          // skd: {
          //   rules: [
          //     { required: true, message: this.$t('financialManagement.selectCollectionOrder')+'!'}
          //   ]
          // }
        },
        url: {
          add: '/accountHead/addAccountHeadAndDetail',
          edit: '/accountHead/updateAccountHeadAndDetail',
          detailList: '/accountItem/getDetailList'
        }
      }
    },
    computed: {
      accountOptionList () {
        const column = this.accountTable.columns.find(item => item.key === 'accountId')
        return column ? column.options : []
      }
    },
    methods: {
      //调用完edit()方法之后会自动调用此方法
      editAfter() {
        this.initSupplier()
        this.billStatus = '0'
        if (this.action === 'add') {
          this.addInit("ZPHX");
          this.$nextTick(() => {
            this.$refs[this.refKeys[0]].initialize()
          })
          this.fileList = []
        } else {
          this.model.billTime = this.model.billTimeStr
          this.$nextTick(() => {
            this.form.setFieldsValue(pick(this.model,'organId', 'handsPersonId', 'billTime', 'billNo', 'remark',
                  'totalPrice', 'changeAmount'))
          });
          
          // 加载子表数据
          let params = {
            headerId: this.model.id
          }
          let url = this.readOnly ? this.url.detailList : this.url.detailList;
          this.requestSubTableData(url, params, this.accountTable);
        }
        this.initRetail()
        this.initPerson()
        this.initDetailAccount()
      },
      initSupplier() {
        let that = this;
        findBySelectCus({}).then((res)=>{
          if(res) {
            that.supList = res;
          }
        });
      },
      
    // 校验jedittable 数字大于0
      validateCheckNumber(type, value, row, column, callback, target) {
        let allValues = target.inputValues
        let currentRow = allValues.find(v=>v.id.includes(row.id))
        console.log('currentRow :>> ', currentRow);
        if(+value <= 0 && currentRow && !currentRow.sourceId){
          callback(false,this.$t('otherJS.greaterThan0'))
          return
        }else if(currentRow && currentRow.sourceId && (value === '' || +value !== 0)){
          callback(false,this.$t('otherJS.giftPrice0'))
        } else{
          callback(true)
        } 
      },
      onChange ({row, target}) {
        target.getValues((err, values) => {
          const data = values[0]
          this.accountTable.dataSource.forEach(item => {
            if (item.billNo === data.billNo) {
              item.notReceived = data.notReceived
            }
          })
          console.log('this.accountTable.dataSource :>> ', this.accountTable.dataSource);

          this.calcChangeAmount()
        }, true,[row.id])
      },
      //提交单据时整理成formData
      classifyIntoFormData(allValues) {
        let billMain = Object.assign(this.model, allValues.formValue);
        let detailArr = allValues.tablesValue[0].values
        billMain.type = '支票核销'
        billMain.subType = '支票核销'

        if(billMain.accountId === 0) {
          billMain.accountId = ''
        }
        if(this.fileList && this.fileList.length > 0) {
          billMain.fileName = this.fileList
        } else {
          billMain.fileName = ''
        }
        if(this.model.id){
          billMain.id = this.model.id
        }
        billMain.status = this.billStatus
        billMain.totalPrice = billMain.changeAmount
        billMain.changeAmount = billMain.changeAmount
        billMain.creator =  this.$attrs.userList.find(item => item.userName === billMain.userName).id
        detailArr.forEach(item => {
          item.eachAmount = item.notReceived 
          item.finishDebt = item.checkAmount
          item.needDebt = item.totalPrice
          item.invoiceNo = item.taxInvoiceNo
          item.billNumber = item.billNo
        })

        let fileList = JSON.stringify(JSON.parse(localStorage.getItem("fileList")))
        return {
          info: JSON.stringify(billMain),
          attachment: fileList,
          rows: JSON.stringify(detailArr),
        }
      },
      addCustomer () {
      this.$refs.customerModalForm.add()
      this.$refs.customerModalForm.title =
        '新增客户（提醒：如果找不到新添加的客户，请到用户管理检查是否分配了该客户权限）'
      this.$refs.customerModalForm.disableSubmit = false
    },
      onSearchLinkNumber() {
        let organId = this.form.getFieldValue('organId')
        // this.$refs.linkBillList.show('其它', this.$t('manuManagement.purchaseOrder'), this.$t('warehouseManagement.supplier'), "1,3", organId)
        this.$refs.linkBillList.acceptanceShow('其它', '支票核销', this.$t('manuManagement.customer'), "2", organId, this.prefixNo)
        this.$refs.linkBillList.title = this.$t('financialManagement.checkVerification')
      },
      linkBillListOk (selectedRow) {
        const list = selectedRow.map(item => {
          item.notReceived = this.__substraction(item.totalPrice, item.checkAmount)
          item.custom1 = item.id
          return item
        })
        this.accountTable.dataSource = list
        this.$nextTick(()=>{
          let item = this.supList.find(v=>v.supplier === selectedRow[0].supplier)
          this.form.setFieldsValue({
            'organId':(item && item.id) || ''
          })
        })
        this.calcChangeAmount()
      },
      calcChangeAmount () {
        console.log('this.accountTable.dataSource :>> ', this.accountTable.dataSource);
        let num =  this.accountTable.dataSource.reduce((pre, cur) => {
          return this.__addition(pre, cur.notReceived)
        }, 0)
        this.$nextTick(() => {
          this.form.setFieldsValue({
            changeAmount: num
          })
        })
      },
      openDetail (record) {
        let detail = record.allValues.inputValues[0]
        this.$refs.modalDetail.show(record.value,detail.type)
        this.$refs.modalDetail.title = this.$t('financialManagement.checkVerification')
      },
      removeRows (text) {
        this.$refs[this.refKeys[0]].removeRows(text.rowId)
      }
    }
  }
</script>
<style scoped lang="less">
::v-deep .ant-spin-container .thead {
  background: #beddf9;
  & > .tr > .td {
    border-left: 1px solid #f2f2f2;
    text-align: center;
  }
}
</style>